package cn.gezi.zhiqiu.core.common.controller;

import cn.gezi.zhiqiu.core.util.JwtTokenUtil;
import cn.gezi.zhiqiu.modular.system.entity.User;
import cn.gezi.zhiqiu.modular.system.model.UserDto;
import cn.gezi.zhiqiu.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestHeader;

/**
 * ApiController基类
 * @author 知秋
 */
@Component
public class ApiBaseController extends BaseController {

    @Autowired
    private UserService userService;

    private UserDto userDto;

    /**
     * 获得token授权的用户
     * @param headers
     * @return
     */
    @ModelAttribute
    private void init(@RequestHeader HttpHeaders headers){
        Long userId = Long.parseLong(
                JwtTokenUtil.getUsernameFromToken(headers.getFirst("Authorization")));
        if(!ObjectUtils.isEmpty(userId)){
            User user = userService.getById(userId);
            userDto = new UserDto();
            BeanUtils.copyProperties(user, userDto);
        }
    }

    /**
     * 获得用户信息
     * @return
     */
    protected UserDto getUser(){
        return userDto;
    }
}
